import { createVNode, defineComponent, ref, render } from 'vue'
import { getServerType } from '@/lib/js/http'
import { ServerTypeEnum } from '@/lib/js/http/enums'
import { LoginLocalStorageKey } from '@/lib/js/hooks/useLogin'
import { goLogin, smsCode } from './api'
import { Toast } from 'vant'
import './index.scss'

type Suc = null | undefined | ((signature: string) => void);

let isCreate: boolean
let loginHandle: Suc = null

const visible = ref(false)

const isPhone = (phone: string) => /^\d{11}$/.test(phone)

const isCode = (code: string) => /^\d{4}$/.test(code)

const checkPhone = (phone: string | null) => {
  if (!phone) {
    Toast('请输入手机号码')
    return false
  }

  if (!isPhone(phone)) {
    Toast('请输入正确的手机号码')
    return false
  }

  return true
}

const checkCode = (code: string | null) => {
  if (!code) {
    Toast('请输入验证码')
    return false
  }

  if (!isCode(code)) {
    Toast('请输入正确验证码')
    return false
  }

  return true
}

const loginSuccess = ({ key, signature, SessionId }: {key: string; signature?: string; SessionId?: string;}) => {
  localStorage.setItem(LoginLocalStorageKey.key, key)
  signature && localStorage.setItem(LoginLocalStorageKey.signature, signature)
  SessionId && localStorage.setItem(LoginLocalStorageKey.session, SessionId)
  loginHandle && loginHandle(key)
}

const ComLogin = defineComponent({
  name: 'Login',

  setup() {
    
    const formData = {
      phone: null,
      code: null
    }

    const change = () => {
      visible.value = !visible.value
    }

    const changePhone = (e: any) => {
      formData.phone = e.target.value
    }

    const changeCode = (e: any) => {
      formData.code = e.target.value
    }

    const wait = ref(0)

    const sendVerify = () => { // 发送验证码
      if (checkPhone(formData.phone)) {
        smsCode(Number(formData.phone)).then(() => {
          Toast.success('发送成功')
          wait.value = 60
          const timer = setInterval(() => {
            if (wait.value === 0) {
              clearInterval(timer)
              return false
            }
            wait.value -= 1
          }, 1000)
        })
      }
    }


    const submit = () => { // 登录and注册
      if (checkPhone(formData.phone) && checkCode(formData.code)) {
        goLogin(Number(formData.phone), Number(formData.code)).then(data => {
          const type = getServerType()
          if(type === ServerTypeEnum.old) {
            const { result: { signature, k } } = data
            loginSuccess({ key: k, signature })
          }
          if(type === ServerTypeEnum.new) {
            const { Key, SessionId } = data
            loginSuccess({ key: Key, SessionId })
          }
          if(type === ServerTypeEnum.zhangkai) {
            const {result: {k, signature}} = data
            loginSuccess({ key: k, signature })
          }
          change()
        })
      }
    }

    return () => (
      <>
        {
          visible.value && (<section class="login_pop">
            <div class="login animated">
              <h1>登录/注册账号</h1>
              <div class="content">
                <div class="item">
                  <span class="label">手机号码</span>
                  <input name="phone" 
                  type="tel" 
                  onInput={changePhone} 
                  placeholder="请输入手机号码" />
                </div>
                <div class="item">
                  <span class="label">验证码</span>
                  <input name="code" type="number" onInput={changeCode} placeholder="请填写短信验证码" />
                  {
                    wait.value ? (<span class='btn'>{wait.value}S</span>) : (<span class='btn' onClick={sendVerify}>发送验证码</span>)
                  }
                </div>
              </div>
              <div class="btn_box">
                <div class="cancel" onClick={change}>取消</div>
                <div class="submit" onClick={submit}>登录</div>
              </div>
            </div>
          </section>)
        }
      </>
    )
  }
})

export const createLogin = (loginSuc?: Suc) => {
  const isHH = window.isHeyHeyTalk && window.isHeyHeyTalk()
  const { HeyheyBridge } = window
  if (isHH) {
    HeyheyBridge.request({ action: 'login', data: '' }, (e: any) => {
      try {
        const data = JSON.parse(e.data);
        if (Number(data.Role) === 2) { // 游客处理
          window.location.href = 'heyheytalk://login'
          return false
        }
        loginSuccess({ key: data.Key })
      } catch (err) {
        if (e === null) { // 注册失败
          window.location.reload()
          return false
        }
      }
    })
  } else {
    loginHandle = loginSuc
    if (!isCreate) {
      const container = document.createElement('div')
      container.id = 'login'
      const vm = createVNode(ComLogin)
      render(vm, container)
      document.body.appendChild(container)
      isCreate = true
    }
    visible.value = true
  }
}
